﻿using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using ReadyApps.Data;

namespace ReadyApps.Wiki.Views
{
    class NewSiteView : DataViewBase, IViewFiresTitleSetEvent
    {
        #region Variables and Constants

        private const string SECURITY_ENABLED_CONTROL_ID = "chkSecurityEnabled";
        private const string CREATOR_TEXT_CONTROL_ID = "txtCreator";
        private const string CREATOR_HIDDEN_CONTROL_ID = "hdnCreator";
        private const string CREATE_VALIDATION_GROUP = "vgCreate";

        private CheckBox chkSecurityEnabled;
        private TextBox txtCreator;
        private HiddenField hdnCreator;
        private IWikiSecurityManager securityManager;
        private string siteName;
        private string baseFolder;

        #endregion

        #region Events

        private event EventHandler<CreateNewSiteEventArgs> createButtonClick;
        public event EventHandler<CreateNewSiteEventArgs> CreateButtonClick
        {
            add { createButtonClick += value; }
            remove { createButtonClick -= value; }
        }

        #endregion

        #region Constructor

        public NewSiteView(string siteName, string baseFolder, WikiControlSettings wikiControlSettings,
            IWikiDataProvider wikiDataProvider, IWikiSecurityManager wikiSecurityManager)
            : base(WikiController.IMPOSSIBLE_PAGE_ID, wikiControlSettings, wikiDataProvider)
        {
            if (wikiSecurityManager == null)
            {
                throw new ArgumentNullException("wikiSecurityManager");
            }
            if (string.IsNullOrEmpty(siteName))
            {
                throw new ArgumentNullException("siteName");
            }
            if (string.IsNullOrEmpty(baseFolder))
            {
                throw new ArgumentNullException("baseFolder");
            }
            securityManager = wikiSecurityManager;
            this.siteName = siteName;
            this.baseFolder = baseFolder;
        }

        #endregion

        #region Public Methods

        public override void BuildControlTree(ControlCollection controls, bool raiseEvents)
        {
            Control container = new Control();

            HtmlGenericControl header = new HtmlGenericControl("h1");
            header.InnerText = "New Wiki Site";
            container.Controls.Add(header);

            HtmlGenericControl openingParagraph = new HtmlGenericControl("p");
            openingParagraph.InnerText = @"
It appears that you are trying to access a site that does yet exist. If you believe this to
be an error, confirm the settings on the ASP.Net control. If you would like to create a new
site, choose whether you would like the site to apply security policies to the content and
then click create. A new site will be created with default pages and privileges that you
can then edit through the web interface.
";
            container.Controls.Add(openingParagraph);
            container.Controls.Add(new HtmlGenericControl("hr"));

            container.Controls.Add(GenerateInformationTable());

            if (raiseEvents)
            {
                controlSettings.OnTitleSet(this, new TitleSetEventArgs("New Wiki Site"));
            }

            controls.Clear();
            controls.Add(container);
        }

        #endregion

        #region Private Methods

        private Table GenerateInformationTable()
        {
            Table table = new Table();

            table.Rows.Add(GetSiteNameRow());
            table.Rows.Add(GetBaseFolderRow());
            table.Rows.Add(GetCreatorRow());
            table.Rows.Add(GetSecurityEnabledRow());
            table.Rows.Add(GetCreateButtonRow());

            return table;
        }

        private TableRow GetSiteNameRow()
        {
            TableRow row = new TableRow();

            row.Cells.Add(new TableCell() { Text = "Site Name:" });
            row.Cells.Add(new TableCell() { Text = siteName });

            return row;
        }

        private TableRow GetBaseFolderRow()
        {
            TableRow row = new TableRow();

            row.Cells.Add(new TableCell() { Text = "Folder Path:" });
            row.Cells.Add(new TableCell() { Text = baseFolder });

            return row;
        }

        private TableRow GetCreatorRow()
        {
            TableRow row = new TableRow();

            row.Cells.Add(new TableCell() { Text = "Site Creator:" });
            TableCell cell = new TableCell();
            if (securityManager.IsUserAuthenticated)
            {
                hdnCreator = new HiddenField();
                hdnCreator.ID = CREATOR_HIDDEN_CONTROL_ID;
                hdnCreator.Value = securityManager.CurrentUsername;
                cell.Controls.Add(hdnCreator);
                cell.Controls.Add(new Literal() { Text = securityManager.CurrentUsername });
            }
            else
            {
                txtCreator = new TextBox();
                txtCreator.ID = CREATOR_TEXT_CONTROL_ID;
                RequiredFieldValidator rfvCreator = new RequiredFieldValidator();
                rfvCreator.ControlToValidate = CREATOR_TEXT_CONTROL_ID;
                rfvCreator.ValidationGroup = CREATE_VALIDATION_GROUP;
                cell.Controls.Add(txtCreator);
            }
            row.Cells.Add(cell);

            return row;
        }

        private TableRow GetSecurityEnabledRow()
        {
            TableRow row = new TableRow();

            TableCell cell = new TableCell();
            cell.ColumnSpan = 2;
            cell.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
            chkSecurityEnabled = new CheckBox();
            chkSecurityEnabled.ID = SECURITY_ENABLED_CONTROL_ID;
            chkSecurityEnabled.Text = "Enable security on the new site";
            cell.Controls.Add(chkSecurityEnabled);
            row.Cells.Add(cell);

            return row;
        }

        private TableRow GetCreateButtonRow()
        {
            TableRow row = new TableRow();

            TableCell cell = new TableCell();
            cell.ColumnSpan = 2;
            cell.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
            Button createButton = new Button();
            createButton.Text = "Create Site";
            createButton.ValidationGroup = CREATE_VALIDATION_GROUP;
            createButton.Click += new EventHandler(createButton_Click);
            cell.Controls.Add(createButton);
            row.Cells.Add(cell);

            return row;
        }

        private void createButton_Click(object sender, EventArgs e)
        {
            if (createButtonClick != null)
            {
                string creator = txtCreator != null ? txtCreator.Text : hdnCreator.Value;
                createButtonClick(this, new CreateNewSiteEventArgs(chkSecurityEnabled.Checked, creator));
            }
        }

        #endregion
    }
}
